package com.yowasa.xiuxian.engine.message.activity;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.ruiyun.jvppeteer.util.StringUtil;
import com.yowasa.xiuxian.annoations.CMD;
import com.yowasa.xiuxian.engine.message.CmdMessageHandler;
import com.yowasa.xiuxian.entity.mys.MysComponent;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import com.yowasa.xiuxian.entity.po.WereWolf;
import com.yowasa.xiuxian.entity.po.WolfTicket;
import com.yowasa.xiuxian.exception.HandlerException;
import com.yowasa.xiuxian.service.helper.MessageHelper;
import com.yowasa.xiuxian.service.helper.UserTagHelper;
import com.yowasa.xiuxian.service.helper.WareHoustHelper;
import com.yowasa.xiuxian.util.ComponentUtil;
import com.yowasa.xiuxian.util.RandomUtil;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.yowasa.xiuxian.util.ContentUtil.getIndex;


@CMD(name = "/狼人杀")
public class WerewolfHandler extends CmdMessageHandler {
    public static final Logger logger = LoggerFactory.getLogger(WerewolfHandler.class);
    @Autowired
    private MessageHelper messageHelper;
    @Autowired
    private WareHoustHelper wareHoustHelper;

    private Integer roundTime = 1;

    @Override
    public void execute(SendMessage message) {
        if(Integer.parseInt(message.getVilla_id())!=3568){
            throw new HandlerException("这是原神·星穹茶馆的专属指令！！ 赋宝天下第一可爱！");
        }
        String userId = message.getFrom_user_id();
        String flag = wareHoustHelper.checkAdmin(userId,2);

        List<String> params = getAllParam(message);//获取名称
        if (StringUtils.isEmpty(params.get(0))) {
            messageHelper.replyMys(message, "可以在后面追加 创建房间 报名 开始游戏 结束游戏等二级指令进行后续操作\n\n具体指令示例：\n" +
                    "/创建房间 10   创建房间 + 人数\n/报名 2987   报名 + 房间号\n/开始游戏 2987   开始游戏 + 房间号\n/结束游戏 2987  结束游戏 + 房间号\n\n游玩结束后请一定使用结束游戏指令将身份组收回，开始游戏前请务必确认身份组中没有其他人");
            return;
        }
        if ("创建房间".equals(params.get(0))) {
            if(flag == null){
                throw new HandlerException("赋宝还没给你授权呢，无法使用该指令哦");
            }
            int i = RandomUtil.randomInt(10000, 99999);
            Integer a = 12;
            try {
                a = Integer.parseInt(params.get(1));
            }catch (Exception e){
                a = 12;
            }
            //入库
            wareHoustHelper.insertWolfRoom(userId,i,a);

            messageHelper.replyMys(message, "创建成功，如未输入数字则自动创建12人房间，房间号为"+i+"\n报名，开始游戏，结束游戏时间均需要带上此房间号");

        }
        if ("报名".equals(params.get(0))) {
            String nickname = message.getNickname();

            WereWolf one = checkRoom(params,1);
            //房间限制人数
            int i = Integer.parseInt(one.getUserName());
            //当前房间内人数
            int j = wareHoustHelper.selectWolfCount(one.getRoomId());

            if(i <= j){
                throw new HandlerException("人数已满，报名截止，可艾特管理员开启游戏");
            }else {
                wareHoustHelper.insertWolfMember(userId,one.getRoomId(),nickname);
                messageHelper.replyMys(message,"报名成功！");
            }
        }
        if ("取消报名".equals(params.get(0))) {
            WereWolf one = checkRoom(params,1);
            WereWolf list = wareHoustHelper.getUserWolf(one.getRoomId(),userId);
            if(ObjectUtil.isNull(list)){
                throw new HandlerException("你还没报名呢");
            }
            list.setStatus(0);
            wareHoustHelper.updateWolfById(list);
            messageHelper.replyMys(message,"取消报名成功！");
        }
        if ("开始游戏".equals(params.get(0))) {
            if(flag == null){
                throw new HandlerException("赋宝还没给你授权呢，无法使用该指令哦");
            }
            WereWolf one = checkRoom(params,1);
            //房间限制人数
            int i = Integer.parseInt(one.getUserName());
            //当前房间内人数
            int j = wareHoustHelper.selectWolfCount(one.getRoomId());
            if( i != j){
                throw new HandlerException("人数不足，无法开始游戏，当前报名人数："+j+"，房间限制人数："+i);
            }
            List<WereWolf> list = wareHoustHelper.listWolf(one.getRoomId());
            Collections.shuffle(list);
            ArrayList<Integer> idList = Lists.newArrayList(105478, 105480, 105479, 105481, 105482, 105483, 105485, 105486, 105487, 105968, 105969, 105970,119136,120346,120347);
            StringBuilder sb = new StringBuilder();
            sb.append("身份分配完毕！\n");
            ArrayList<Integer> integers = new ArrayList<>();
            for (int index = 0;index<list.size();index++){
                WereWolf e = list.get(index);
                Integer member = idList.get(index);
                e.setMember(member);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("uid",Integer.parseInt(e.getUserId()));
                jsonObject.put("is_add",true);
                jsonObject.put("role_id",member);
                messageHelper.operateMemberToRole(message,jsonObject);
                wareHoustHelper.updateWolfById(e);
                integers.add(index+1);
                sb.append(index+1).append("号 ： ").append(e.getUserName()).append("\n");
            }
            Collections.shuffle(integers);
            int i1 = list.size() / 3;
            List<List<Integer>> partition = Lists.partition(integers, i1);
            sb.append("分配狼为：").append(partition.get(0)).append("\n");
            sb.append("分配神为：").append(partition.get(1)).append("\n");
            sb.append("分配民为：").append(partition.get(2)).append("\n");
            sb.append("仅为随机推荐结果，具体职业与人数请管理员自行调整。");
            one.setStatus(2);
            wareHoustHelper.updateWolfById(one);
            message.setRoom_id(188364);
            messageHelper.replyMys(message,sb.toString());
        }
        if ("结束游戏".equals(params.get(0))) {
            if(flag == null){
                throw new HandlerException("赋宝还没给你授权呢，无法使用该指令哦");
            }
            WereWolf one = checkRoom(params,2);
            one.setStatus(0);
            wareHoustHelper.updateWolfById(one);
            List<WereWolf> list = wareHoustHelper.listWolf(one.getRoomId());
            list.forEach(e -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("uid",Integer.parseInt(e.getUserId()));
                jsonObject.put("is_add",false);
                jsonObject.put("role_id",e.getMember());
                messageHelper.operateMemberToRole(message,jsonObject);

                e.setStatus(0);
                wareHoustHelper.updateWolfById(e);
            });
            roundTime = 1;
            messageHelper.replyMys(message,"本次游玩结束，已将本次参与成员移出身份组");
        }
        if ("授权".equals(params.get(0)) && (userId.equals("299331411") || userId.equals("254576762")) ) {
            String atUserId = messageHelper.getMysContentAtUserId(message.getContent());
            if (StringUtil.isEmpty(atUserId)) {
                throw new HandlerException("需要at对方才能授权");
            }
            wareHoustHelper.insertWolfEmpower(atUserId,2);
            messageHelper.replyMys(message,"授权成功");
        }
        if ("取消授权".equals(params.get(0)) && (userId.equals("299331411") || userId.equals("254576762")) ) {
            String atUserId = messageHelper.getMysContentAtUserId(message.getContent());
            if (StringUtil.isEmpty(atUserId)) {
                throw new HandlerException("需要at对方才能取消授权");
            }
            wareHoustHelper.deleteWolfEmpower(atUserId,2);
            messageHelper.replyMys(message,"取消授权成功");
        }
        if ("查看".equals(params.get(0))) {
            if(flag == null){
                throw new HandlerException("赋宝还没给你授权呢，无法使用该指令哦");
            }
            WereWolf one = checkRoom(params,1);
            //房间限制人数
            int i = Integer.parseInt(one.getUserName());
            List<WereWolf> list = wareHoustHelper.listWolf(one.getRoomId());

            StringBuffer sb = new StringBuffer();

            sb.append("当前房间号：").append(one.getRoomId())
                    .append("\n房间限制人数为：").append(i)
                    .append("\n当前房间内人数：").append(list.size())
                    .append("\n当前房间内成员：\n");
            list.forEach(e -> {
                sb.append(e.getUserName()).append("\n");
            });
            messageHelper.replyMys(message, sb.toString());

        }
        if ("修改房间".equals(params.get(0))) {
            if(flag == null){
                throw new HandlerException("赋宝还没给你授权呢，无法使用该指令哦");
            }
            WereWolf one = checkRoom(params,1);
            //当前房间内人数
            int j = wareHoustHelper.selectWolfCount(one.getRoomId());
            Integer num ;
            try {
                num = Integer.parseInt(params.get(2));
            }catch (Exception e){
                throw new HandlerException("人数上限输入有误");
            }

            if(num < j){
                throw new HandlerException("当前房间内人数为："+j+",不可小于该值");
            }

            one.setUserName(num+"");
            wareHoustHelper.updateWolfById(one);
            messageHelper.replyMys(message,"修改人数上限成功");
        }
        if ("踢人".equals(params.get(0))) {
            if(flag == null){
                throw new HandlerException("赋宝还没给你授权呢，无法使用该指令哦");
            }
            try {
                String s = params.get(1);
                long l = Long.parseLong(s);

                messageHelper.removeMember(message,l);
                messageHelper.replyMys(message,"踢出成功");

            }catch (Exception e){
                throw new HandlerException("输入有误");
            }
        }
        if ("开始投票".equals(params.get(0))) {
            if(flag == null){
                throw new HandlerException("赋宝还没给你授权呢，无法使用该指令哦");
            }
            WereWolf one = checkRoom(params,2);
            List<WereWolf> list = wareHoustHelper.getLiveWolf(one.getRoomId());
            ArrayList<Integer> idList = Lists.newArrayList(105478, 105480, 105479, 105481, 105482, 105483, 105485, 105486, 105487, 105968, 105969, 105970,119136,120346,120347);
            List<Integer> collect = list.stream().map(e -> {
                int i = idList.indexOf(e.getMember()) + 1;
                return i;
            }).collect(Collectors.toList());

            List<MysComponent> components = new ArrayList<>();
            for (int i = 0 ;i < list.size();i++){
                MysComponent component = new MysComponent((i+1)+"",1,collect.get(i)+"","111");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("key","狼人杀投票");
                jsonObject.put("number",collect.get(i));
                jsonObject.put("round",roundTime);
                jsonObject.put("roomId",one.getRoomId());
                component.setExtra(jsonObject.toString());
                components.add(component);
            }

            List<List<MysComponent>> partition = Lists.partition(components, 9);
            wareHoustHelper.addTicket(one.getRoomId(),roundTime);
            partition.forEach(e -> {
                MysComponent[] mysComponents = e.toArray(new MysComponent[]{});
                List<List<MysComponent>> lists = ComponentUtil.genComponentList(3, mysComponents);
                messageHelper.replyMysPanel(message,"第"+roundTime+"轮投票",lists,null,null);
            });
            roundTime++;
        }
        if ("结束投票".equals(params.get(0))) {
            if(flag == null){
                throw new HandlerException("赋宝还没给你授权呢，无法使用该指令哦");
            }
            WereWolf one = checkRoom(params,2);
            List<Map<String, String>> map = wareHoustHelper.listTicket(one.getRoomId(), roundTime - 1);
            StringBuffer sb = new StringBuffer();
            sb.append("投票结果为：\n");
            map.forEach(e -> {
                sb.append(e.get("userList")).append("-->>").append(e.get("choose")).append("\n");
            });

            messageHelper.replyMys(message,sb.toString());
        }
        if ("死亡".equals(params.get(0))) {
            if(flag == null){
                throw new HandlerException("赋宝还没给你授权呢，无法使用该指令哦");
            }
            WereWolf one = checkRoom(params,2);
            List<String> list = messageHelper.getAllMysContentAtUserId(message.getContent());
            list.forEach(e -> {
                WereWolf wereWolf = new WereWolf();
                wereWolf.setDead(1);
                LambdaQueryWrapper<WereWolf> eq = new LambdaQueryWrapper<WereWolf>().eq(WereWolf::getRoomId, one.getRoomId()).eq(WereWolf::getUserId,e);
                wareHoustHelper.updateWolf(wereWolf,eq);
            });
            messageHelper.replyMys(message,"已将所艾特玩家标记为死亡，投票时将不会出现");
        }
        if ("投票复盘".equals(params.get(0))) {
            if(flag == null){
                throw new HandlerException("赋宝还没给你授权呢，无法使用该指令哦");
            }
            WereWolf one = checkRoom(params,2);
            List<List<Map<String, String>>> lists = wareHoustHelper.reviewTicket(one.getRoomId());
            StringBuffer sb = new StringBuffer();

            lists.forEach(getIndex((e, index) -> {
                sb.append("第").append(index+1).append("轮投票结果：\n");
                e.forEach(q -> {
                    sb.append(q.get("userList")).append("-->>").append(q.get("choose")).append("\n");
                });
            }));
            messageHelper.replyMys(message,sb.toString());
        }
    }

    private WereWolf checkRoom(List<String> params, int i) {
        Integer roomId ;
        try {
            roomId = Integer.parseInt(params.get(1));
        }catch (Exception e){
            throw new HandlerException("输入的房间号有误");
        }
        WereWolf one = wareHoustHelper.getWolfRoom(roomId,i);
        if(ObjectUtil.isNull(one)){
            throw new HandlerException("该房间不存在");
        }
        return one;
    }


    public String desc() {
        return "深渊挑战";
    }


}
